// pages/homepage/homepage.js
import { picUrl, formatTime, launchAppCopy,dataHandleNull} from '../../utils/util.js';
import { getUserInfo, leftActivityStatus, myConferences } from '../../utils/getData.js';
import { uploadFile } from '../../utils/uploadFile.js';
const getopen = require('../../utils/maxutil.js');

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isliuhai:app.globalData.isliuhai, //是否有刘海
    headerTop:getApp().globalData.headerTop, //导航距离顶部的距离
    currentTab:0, //tab看自己 默认照片墙，看别人所有局
    winHeight: 508, //tab切换内容区域高度
    avatar:'', //头像
    userName:'', //姓名
    sign:'', //标志
    college:'', //学校
    fensiNums:'', //粉丝数
    guanzhuNums:'', //关注数
    pictureInfoVos:'', //照片墙
    allConferenceInfoVos:[], //所有局列表
    status:1, //1未认证, 2已认证
    cardData:{},//卡片上的数据
    islookme:true, //是否查看自己的个人主页
    userTags:[],
    age:0,

    blurrybj:'',//模糊过的背景图
    joinType:0, //加入状态0不显示弹框 1成功加入，2申请已成功提交
    dropOut:false, //退出按钮状态
    juInvalidation:1, //局是否失效 1失效，2未失效

    bubblePopover:0, //冒泡弹框 0不显示弹框 1进入有局，2退出
    previewImage:[], //查照片墙朋友圈效果图片列表

    pageNum:2, //起始页数
    userInfo:null

  },

  
/**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let id = options.userid ? options.userid : wx.getStorageSync('userId'); //有值是看别人的主页，没值时看自己的主页
      if(wx.getStorageSync('userId')){
        this.getUserInfodata(id);
      }else{
        //未注册的用户
        wx.navigateTo({
          url: '../login/login'
        })
      }

    var that = this;
        /**
         * 获取当前设备的宽高
         */
        wx.getSystemInfo( {
            success: function( res ) {
              console.log('设备的宽高'+res.windowHeight)
              if(res.windowHeight < 895)
                that.setData( {
                    winHeight: res.windowHeight - 321
                });
            }
        });
        

  },
  //  tab切换逻辑
  swichNav: function( e ) {
    var that = this;

    if( this.data.currentTab === e.target.dataset.current ) {
      return false;
    } else {
        that.setData( {
          currentTab: e.target.dataset.current
        })
    }
  },
  //tab主体部份滑动事件
  bindChange: function( e ) {
    var that = this;
    that.setData( { currentTab: e.detail.current });
  },

  //获取用户信息
  getUserInfodata(id){
  let than = this;
  let data = {
    lookUserId:wx.getStorageSync('userId'),//谁去看
    userId:id, 
  }
  getUserInfo(data).then(res=> {
    if(!res.success){
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 1000
      })
      return false;
    }
    let newdata = dataHandleNull(res.result);

    let previewImage = [];
    let pictureInfoVos = newdata.pictureInfoVos.map((item)=> {
      previewImage.push(picUrl('',item.content))
      return{...item, content:picUrl('',item.content),isEdit:false}
    })
    let age = this.getAge(newdata.birthDay)
    than.setData({
      // previewImage,
      userTags:newdata.userTags.split(","),
      userInfo:newdata,
      age:age,
      avatar:newdata.avatar? picUrl('',newdata.avatar) : app.globalData.wxuserinfo.avatarUrl, //头像
      userName:newdata.userName? newdata.userName : app.globalData.wxuserinfo.nickName, //姓名
      sign:newdata.sign, //标志
      college:newdata.college, //学校
      fensiNums:newdata.fensiNums, //粉丝数
      guanzhuNums:newdata.guanzhuNums, //关注数
      pictureInfoVos:pictureInfoVos, //照片墙
      // allConferenceInfoVos:newallConferenceInfoVos, //所有局列表
      status:newdata.status, //1未认证, 2已认证
      islookme:wx.getStorageSync('userId') && id == wx.getStorageSync('userId'), //是否查看自己的个人主页
      currentTab:id == wx.getStorageSync('userId') ? 0: 1, //tab看自己 默认照片墙，看别人所有局
    })

    
    than.turnData(newdata.allConferenceInfoVos);

    console.log(newdata)

  })

},

//根据生日获取年龄
getAge(strBirthday) {
  var returnAge = '';
  var mouthAge = '';
  var strBirthdayArr = strBirthday.split("-");
  var birthYear = strBirthdayArr[0];
  var birthMonth = strBirthdayArr[1];
  var birthDay = strBirthdayArr[2];
  var d = new Date();
  var nowYear = d.getFullYear();
  var nowMonth = d.getMonth() + 1;
  var nowDay = d.getDate();
  if (nowYear == birthYear) {
    // returnAge = 0; //同年 则为0岁
    var monthDiff = nowMonth - birthMonth; //月之差 
    if (monthDiff < 0) {
    } else {
      mouthAge = monthDiff + '个月';
    }
  } else {
    var ageDiff = nowYear - birthYear; //年之差
    if (ageDiff > 0) {
      if (nowMonth == birthMonth) {
        var dayDiff = nowDay - birthDay; //日之差 
        if (dayDiff < 0) {
          returnAge = ageDiff - 1 + '岁';
        } else {
          returnAge = ageDiff + '岁';
        }
      } else {
        var monthDiff = nowMonth - birthMonth; //月之差 
        if (monthDiff < 0) {
          returnAge = ageDiff - 1 + '岁';
        } else {
          mouthAge = monthDiff + '个月';
          returnAge = ageDiff + '岁';
        }
      }
    } else {
      returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
    }
  }
  return returnAge + mouthAge; //返回周岁年龄+月份
},

//转数据
turnData(data){
  const { allConferenceInfoVos } = this.data;
  console.log(data)
  
  //判断局是否结束
  let currentTime = formatTime(new Date()); //当前时间
  currentTime = currentTime.substring(0, currentTime.length - 9);
  

  let newDatd =  data.map((item)=> {

    let activityEndTime = item.conferenceDate.replace(/-/g, "/") //局结束时间
    return {
      activityInvalidation: currentTime > activityEndTime, //局是否失效
      activityBlurCoverPage: picUrl('activity/img/', item.conferenceBlurCoverPage),
      activityCoverPage: picUrl('activity/img/', item.conferenceCoverPage),
      activityAddress: item.conferenceAddress.split(',')[0],
      activityBeginTime: item.conferenceBeginTime,
      activityDate: item.conferenceDate.slice(5).replace(/-/g, "/"),
      activityEndTime: item.conferenceEndTime,
      activityId: item.conferenceId,
      activityImageRGB: item.conferenceRGB, //
      activityJoinType: item.conferenceJoinType,
      activityMaxNums: item.conferenceMaxNums,
      activityName: item.conferenceName,
      activityRGB: item.conferenceRGB,
      conferenceType: item.conferenceType, //是否为大型活动
      // islock: false, //是否为第一次跳转大型活动， false--未锁定  true--锁定
      guanzhu: item.guanzhu, //
      join: item.join, //
      shareImg: picUrl('activity/img/', item.shareImg), //
      activityUsedNums: item.conferenceUsedNums,
      activityUserMap: item.conferenceUserMap.participantlist,
      sponsorId: item.sponsorId,
      sponsorUser: {
        ...item.sponsorUser,
        avatarPath: picUrl('', item.sponsorUser.avatarPath),
        authImgPath: picUrl('activity/img/', item.sponsorUser.authImgPath),
        userPic: picUrl('activity/img/', item.sponsorUser.userPic)
      },
    }
    // return {...item, 
    //   conferenceAddress:item.conferenceAddress.split(',')[0],
    //   conferenceCoverPage:picUrl('activity/img/',item.conferenceCoverPage), 
    //   conferenceBlurCoverPage:picUrl('activity/img/',item.conferenceBlurCoverPage),
    //   conferenceDate:item.conferenceDate.slice(5).replace("-","/"),
    //   conferenceUserMap:item.conferenceUserMap.participantlist.map((b)=>{
    //     return {...b, avatarPath:picUrl('',b.avatarPath), userPic:picUrl('',b.userPic)}
    //   }),
    // }
    
  })


  let newDatdtwo = newDatd.map((b) => {
    return {
      ...b,
      activityUserMap: b.activityUserMap && b.activityUserMap.map((c) => {
        return {
          ...c,
          authImgPath: picUrl('', c.authImgPath),
          avatarPath: picUrl('', c.avatarPath),
          userPic: picUrl('', c.userPic)
        }
      })
    }
  })
console.log(newDatdtwo)
  this.setData({
    allConferenceInfoVos:allConferenceInfoVos.concat(newDatdtwo)
  })
},
//编辑个人信息
eidtuserinfo(){

  wx.navigateTo({
    url: '../eidtuserinfo/eidtuserinfo?userinfo='+this.data.userInfo
  })
  
},
// 所有局列表点击事件
goinfo(event){
  const { allConferenceInfoVos } = this.data;
  let than = this;
  let conferenceId = event.currentTarget.dataset.conferenceid;
  let conferenceName = event.currentTarget.dataset.conferencename;
  let userId = event.currentTarget.dataset.userid;
  let userName = event.currentTarget.dataset.username;
  let conferenceType = event.currentTarget.dataset.conferencetype;
  let index = event.currentTarget.dataset.index;
  
  
  app.globalData.userInfo.activityId = conferenceId
  app.globalData.userInfo.activityName = conferenceName
  app.globalData.userInfo.userName = userName
  app.globalData.userInfo.userId = userId

  // 使手机振动15ms
  wx.vibrateShort();

  if(wx.getStorageSync('status') == 0){
    //未注册的用户
  wx.navigateTo({
    url: '../login/login'
  })
  return false
  }
  if(wx.getStorageSync('status') == 9){
    //未注册的用户
  wx.navigateTo({
    url: '../releaseAvatar/releaseAvatar'
  })
  return false
  }

  //大型活动
  if(conferenceType == 1){
    wx.navigateTo({
      url: '../bureau/bureau?conventionId=' + conferenceId
    })
    return false 
  }else{//局详情
    wx.navigateTo({
      url: '../czqhomedetail/czqhomedetail?activityId=' + conferenceId
    })

    return false
  }

  // if(conferenceType == 2){
  //   than.setData({
  //     cardData:allConferenceInfoVos[index], //卡片上的数据
  //     juInvalidation:allConferenceInfoVos[index].activityInvalidation
  //     // juInvalidation: currentTime >= activityEndTime ? 1 : 2, //局是否失效
  //   },()=>{

  //   //控制背景 显示
  //   than.setData({
  //     isjubjshow:true,
  //     // jubjOut:false,
  //     jubjIn:true,
  //     joinType:1,
  //     dropOut:allConferenceInfoVos[index].join, //是否能退出
  //   })

  //   })

  // }else{
  //   //大型活动
  //   wx.navigateTo({
  //     url: '../bureau/bureau?conventionId='+conferenceId
  //   })
  // }
  
  
},
gonext(){
  console.log('sfsfsaf')
  this.myConferences();
},
//参加、主办、喜欢集会列表
myConferences(){
  const { pageNum }  = this.data;
  let than = this;
  let data ={
    pageNum, //起始页数
    pageSize:'5', //每页行数
    type:1, //1-所有 2-喜欢
    userId:wx.getStorageSync('userId')
  }
  myConferences(data).then(res=> {
    console.log('参加、主办、喜欢集会列表')
    if(res.success){
      than.turnData(res.result.records)
      this.setData({
        pageNum:this.data.pageNum +1
      })

    }
  })
},

  //右下角退出
  out(){
    this.setData({
      bubblePopover:2
    })
  },
  // 退出局  
  outju(){
  let than = this;
  let data = {
    activityId:app.globalData.userInfo.activityId,
    userId:wx.getStorageSync('userId') || '', //微信获取，非必填项
  }
  leftActivityStatus(data).then(res=> {
    if(res.success){
      than.setData({
        bubblePopover:0,
        jubjIn:false,
        isjubjshow:false,
        joinType:0,
        dropOut:false,
      })
    }else{
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }
  })
  },
  //透明背景事件
  ontransparentBj(){
    this.setData({
      bubblePopover:0
    })
  },

//  打开有局app链接
openApp(){
  console.log('打开有局app')
},

  //有局app弹框上的按钮事件
  launchAppError(e){
    console.log(7777)
    //复制文字到剪贴板
    launchAppCopy()
  },
//增加个人照片
addPhoto(e){
  console.log(e.currentTarget.dataset.url)
  //点自己照片时
  if(!this.data.islookme){
    //全屏预览图片
    wx.previewImage({
      urls: [e.currentTarget.dataset.url],
    })
    return false;
  }
  
  this.setData({
    bubblePopover:1
  })
},
//编辑层显示
editPhotoShow(e){
  const { pictureInfoVos } = this.data;
  let idx = e.target.dataset.idx;
  pictureInfoVos[idx].isEdit = true
  this.setData({
    pictureInfoVos
  })
},
//取消
cancelPhoto(e){
  const { pictureInfoVos } = this.data;
  let idx = e.target.dataset.idx;
  pictureInfoVos[idx].isEdit = false
  this.setData({
    pictureInfoVos
  })
},
//编辑事件，上传照片
editPhoto(e){
  wx.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album'],
    success (res) {
      // tempFilePath可以作为img标签的src属性显示图片
      let tempFilePaths = res.tempFilePaths

      console.log(tempFilePaths)
      let params = {
        userId:wx.getStorageSync('userId'),
        pictureId:1,
        fileUpload:tempFilePaths[0],
      }
      uploadFile('user/uploadUserImg','1',params).then(res=>{
        console.log('成功回调')
        //取消层
        
      })
      // than.getUploadUserImg(tempFilePaths)
    }
  })
},


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  //卡片取消事件回调 关闭卡片
  _cardClose(){
    console.log('回调了')
    this.setData({
      jubjIn:false,
      isjubjshow:false,
      joinType:0,
      dropOut:false,
    })
  },
  //卡片进入新的个人主页
  _cardnewhome(){
    console.log('点了首页回调')
  },
    /**
   * 预览图片
   */
  // previewImage(e) {
  //   const current = e.target.dataset.src  //获取当前点击的 图片 url
  //   wx.previewImage({
  //     current,
  //     urls: this.data.imgUrls
  //   })
  // },

  goback(){
    wx.navigateBack({
      delta: 1
    })
  },
  solllist(){
    console.log('gundong')
  },
/**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    // let userName = wx.getStorageSync('userName');
    // let activityId = wx.getStorageSync('activityId');
    // let activityName = wx.getStorageSync('activityName');
    let than = this;
    
    return {
      path: 'pages/subBureauDetails/subBureauDetails?activityId='+than.data.cardData.activityId,
      imageUrl: than.data.cardData.shareImg,
    };
     // 用户点击右上角分享给好友,要先在分享好友这里设置menus的两个参数,才可以分享朋友圈
     wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  //用户点击右上角分享朋友圈
  onShareTimeline: function () {
    let than = this;
      return {
        path: 'pages/subBureauDetails/subBureauDetails?activityId='+than.data.cardData.activityId,
        imageUrl: than.data.cardData.shareImg,
        }
    },

})